import urllib.request as ur
import urllib.parse as up
import json
import ssl
context = ssl._create_unverified_context()

'''
百度翻译 中译英
'''

while True:
    word = input('请输入要翻译的中文：')
    data = {
        'kw': word
    }
    data_url = up.urlencode(data).encode('utf-8')

    # 创建Request对象
    request = ur.Request(url='https://fanyi.baidu.com/sug',
                         data=data_url)
    # 得到返回对象
    ret = ur.urlopen(request, context=context).read()
    # print(type(ret))
    # print(ret)

    # 将返回对象转换为dict类型
    ret_python = json.loads(ret)
    # print(type(ret_python))
    # print(ret_python)

    # 若翻译正常，打印翻译结果
    if len(ret_python['data']) > 0:
        print('翻译结果是：', ret_python['data'][0]['v'])
    # 异常处理
    else:
        print('错误：无法翻译，请重新输入')